// 引入WebSocket模块
var ws = require('nodejs-websocket')
var PORT = 8080
var conn1=" "

var net=require('net');
var stop = false;
process.stdin.resume();

  // on就是addListener，添加一个监听事件调用回调函数
// Scream server example:"hi"->"HI!!!",服务器把字母大写
var server = ws.createServer(function(conn){
    //websocket的conn
    conn1=conn;
    console.log('New connection')
    conn.on("text",function(str){
        console.log("Received"+str)
        client.write(buf);
    })
    conn.on("close",function(code,reason){
        console.log("connection closed")
    })
    conn.on("error",function(err){
        console.log("handle err")
        console.log(err)
    })
}).listen(PORT)


  process.stdin.on('data', function(data){
    if(data.toString().trim().toLowerCase()==='stop'){
      stop=true;
      console.log('connection stop\n');
      client.end();
    }else{
      client.write(data);
    }
  });

  var client=net.createConnection(8000,function () {
    console.log('connected to server!\n');
  });
  client.on('data', function(data) {
    console.log(data.toString()+"111");//打印服务器发送的数据

    //发信息到小程序
    boardcast(data);
    console.log(data.length);
  });
  client.on('error', function(err) {
    console.log('Error in connection:'+ err+'\n');
  });
  client.on('close', function() {
    if(! stop) {
      console.log('connection got closed');
    }
  });

function boardcast(str){
    server.connections.forEach(function(conn){
        conn.sendText(str);
    })
}
console.log('websocket server listening on port ' + PORT)